<?php

namespace app\common\validate;

use think\Validate;

class Admin extends Validate
{

    /**
     * 验证规则
     */
    protected $rule = [
        'id' => 'require',
        'username' => 'require|regex:\\d{11}|uniqueUsername',
        'nickname' => 'require',
        'password' => 'require|min:5',
        'email' => 'require|email|uniqueEmail',
        'confirm_password' => 'min:5|confirm:password',
        "old_password" => "require"
    ];

    /**
     * 提示消息
     */
    protected $message = [
        "id.require" => "缺少参数id",
        "username.require" => "请输入手机号码",
        "username.regex" => "手机号码是个错误",
        "username.uniqueUsername" => "手机号码已存在",
        "nickname.require" => "请输入用户昵称",
        "password.require" => "请输入密码",
        "password.min" => "密码长度必须大于5位",
        "email.require" => "请输入email",
        "email.email" => "email格式错误",
        "email.uniqueEmail" => "email已存在",
        "confirm_password.confirm" => "两次密码输入必须一致",
        "old_password.require" => "请输入原密码"
    ];

    /**
     * 字段描述
     */
    protected $field = [
    ];

    /**
     * 验证场景
     */
    protected $scene = [
        'add' => ['username', 'email', 'nickname', 'password'],
        'update' => ['email', 'nickname', 'id'],
        "resetPass" => ['password', 'confirm_password', 'old_password'],
        "self_update" => ["email", "nickname"]
    ];

    public function uniqueUsername($value, $rule, $row)
    {
        $model = new \app\common\model\Admin();
        $query = $model->where("username", $value);
        if (!empty($row['id'])) $query->where("id", "<>", $row['id']);
        $findUser = $query->find();
        if (empty($findUser)) return true;
        return false;
    }

    public function uniqueEmail($value, $rule, $row)
    {
        $model = new \app\common\model\Admin();
        $query = $model->where("email", $value);
        if (!empty($row['id'])) $query->where("id", "<>", $row['id']);
        $findUser = $query->find();
        if (empty($findUser)) return true;
        return false;
    }

}
